#    Tichy
#
#    copyright 2008 Guillaume Chereau (charlie137@gmail.com)
#
#    This file is part of Tichy.
#
#    Tichy is free software: you can redistribute it and/or modify it
#    under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    Tichy is distributed in the hope that it will be useful, but
#    WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
#    General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with Tichy.  If not, see <http://www.gnu.org/licenses/>.


from item import Item
from attribute import Attribute
from application import Application
from service import Service


class Struct(Item):

    fields = []

    @property
    def _fields(self):

        def as_field(x):
            if isinstance(x, Attribute):
                return getattr(self, '_attr_%s' % x.name)
            return x

        return [as_field(x) for x in self.fields]

    def view(self, parent, editable=False, **kargs):
        from tichy import gui
        # XXX: put into design class
        box = gui.VBox(parent, **kargs)
        for field in self._fields:
            field.view(box, editable=editable)
        return box

    def edit(self, parent=None, editable=True):
        yield StructEditorService.get().show(parent, self, editable=editable)

    def create_actor(self):
        actor = super(Struct, self).create_actor()
        actor.new_action("Edit").connect('activated', self._on_edit)
        actor.new_action("View").connect('activated', self._on_edit, False)
        return actor

    def _on_edit(self, actor, contact, editable=True):
        yield self.edit(None, editable=editable)

    def serialize(self):
        return dict((x.name, getattr(self, x.name).serialize()) for
                    x in self.attributes)

    @classmethod
    def unserialize(cls, data):
        assert isinstance(data, dict)
        ret = cls()
        for key, value in data.items():
            assert isinstance(value, basestring)
            setattr(ret, key, value)
        return ret


# XXX: put this into the design service


class StructEditor(Application):

    def run(self, parent, struct, editable=True):
        import tichy

        self.name = "Edit %s" % struct.title if editable else struct.title

        frame = self.view(parent, back_button=True)

        vbox = tichy.gui.VBox(frame, expand=True)
        struct.view(vbox, editable=editable, expand=True)

        yield tichy.Wait(frame, 'back')


class StructEditorService(Service):

    def show(self, parent, struct, editable=True):
        yield StructEditor(parent, struct, editable=editable)
